<?php
# +--------------------------------------------------------
# |Description: 阳光公采接口：订单接口处理类
# +--------------------------------------------------------
# |Company: 北京申合信科技发展有限公司
# +--------------------------------------------------------
# |WebSite: www.shenhexin.com
# +--------------------------------------------------------
# |Author: Akon<18363851918@163.com>
# +--------------------------------------------------------
# |Date: 2017年6月23日
# +--------------------------------------------------------
namespace Api\Controller;
use Think\Controller;

class OrderController extends Controller{
    /**
     * 预下订单接口
     * URL http://api.shenhexin.com/api/order/submit
     * Http Method POST
     * 1、接受预下订单数据
     * 2、将阳光公采商城订单编号另外储存在另一张表中，关联订单表
     * 3、通过商品编号得到商品名称(tostr)、商品价格，名称后面跟小括号，括号里面放数量，多个商品名称用逗号隔开
     * 4、order_item表：商品名称、商品id、商品原价、商品优惠价、商品总价、商品数量、商品编号，关联order表（先添加order表，后添加order_item表）
     * 5、目前，运费设置为0，后期根据实际情况再进行修改
     * 6、预下订单默认不能被编辑，当确认订单之后，才可以进行操作，order表字段status默认dead
     */
    public function submit(){
        $receive = I('post.');
        /**
         * 接收方式不正常，外层为数组，内层为json，所以sku获取不到，导致错误
         * 解决方案：判断传递过来的数组中sku是否为数组，如果不是，则进行处理
         * 接收到的sku格式为：[{&quot;sku&quot;:&quot;G57B666217EA30&quot;,&quot;num&quot;:1,&quot;price&quot;:13.73},{&quot;sku&quot;:&quot;G57B666217EA30&quot;,&quot;num&quot;:1,&quot;price&quot;:13.73}]
         * 1、htmlspecialchars_decode对sku进行解码成正常的json字符串
         * 2、json_decode将json转换成数组
         */
        if(!is_array($receive['sku'])){
            $sku_arr = json_decode(htmlspecialchars_decode($receive['sku']),true);
        }else{
            $sku_arr = $receive['sku'];
        }
        A('Common')->checkAccessToken($receive['token']);                     //校验access_token
        $time = time();
        $order_info = array();
        $order_item = array();
        $itemnum = 0;

        foreach($sku_arr as $key=>$val){
            $price_info = M('goods','sdb_','DB_CONFIG2')->where(array('bn'=>$val['sku']))->field('price,bn')->find();

            if(sprintf('%.2f',$price_info['price'] * 0.95) != $val['price']){
                $res = array(
                    'success' => 'false',
                    'desc' => '预下订单失败，商品价格有误'
                );
                exit(json_encode($res,JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE));
            }
            $itemnum += $val['num'];
            $order_info['skus'][]      = $val['sku'];                    //目前默认没有延保服务
            $order_item[$key]['bn']    = $val['sku'];
            $order_item[$key]['price'] = $val['price'];
            $order_item[$key]['nums']   = $val['num'];
            $order_item[$key]['amount'] = $val['num'] * $val['price'];
        }

        $order_info['total_amount'] = $receive['order_price'];
        $order_info['order_id']    = date('Ymdhis');
        $order_info['skus']        = implode(',',$order_info['skus']);
        $order_info['itemnum']     = $itemnum;
        $order_info['ship_name']   = $receive['name'];
        $order_info['region_path'] = $receive['province'] .','. $receive['city'] .','. $receive['county'];
        $order_info['ship_zip']    = $receive['zip'];
        $order_info['ship_tel']    = $receive['phone'];
        $order_info['ship_mobile'] = $receive['mobile'];
        $order_info['email']       = $receive['email'];
        $order_info['tax_content'] = $receive['invoice_title'];                    //发票
        $order_info['tax_company'] = $receive['invoice_title'];
        $order_info['cost_item']   = $receive['order_price'];
        $order_info['is_confirm'] = 0;

        if($receive['payment'] == 1){
            $order_info['shipping'] = '货到付款';
            $order_info['shipping_id'] = 11;
        }else if($receive['payment'] == 2){
            $order_info['shipping'] = '国库集中支付(转账)';
            $order_info['shipping_id'] = 12;
        }else if($receive['payment'] == 3){
            $order_info['shipping'] = '在线支付';
            $order_info['shipping_id'] = 13;
        }else if($receive['payment'] == 4){
            $order_info['shipping'] = '支票';
            $order_info['shipping_id'] = 14;
        }
        $order_info['cost_item']   = $receive['order_price'];                      //订单金额(包含运费)
        $order_info['status'] = 'active';

        //会员id
        $members_id = M('members','sdb_','DB_CONFIG2')->where(array('access_token'=>$receive['token']))
                                                      ->field('member_id')
                                                      ->find();
        $order_info['member_id']   = $members_id['member_id'];
        //商品数据
        $goods_sql = "SELECT goods_id,bn,name,price FROM sdb_goods WHERE bn in (".addApostropheToString($order_info['skus']).")";
        $good_info = M('','','DB_CONFIG2')->query($goods_sql);
        //商品名称
        foreach($order_item as $key=>$val){
            $tostr[$key] = $good_info[$key]['name'] ."($val[num])";
            $product_id = M('products','sdb_','DB_CONFIG2')->where(array('goods_id'=>$good_info[$key]['goods_id']))->field('product_id')->find();

            $order_item[$key]['product_id'] = $product_id['product_id'];
            $order_item[$key]['name']       = $good_info[$key]['name'];
            $order_item[$key]['order_id']   = $order_info['order_id'];
        }
        //收货地址
        $ship_area = '';
        $ship_addr = '';
        foreach(explode(',',$order_info['region_path']) as $key=>$val){

            $address[] = M('regions','sdb_','DB_CONFIG2')->where(array('region_id'=>$val))->find();
            if($key === 0){
                $ship_area .= 'mainland:'.$address[$key]['local_name'].'/';
            }else if($key == 1){
                $ship_area .= $address[$key]['local_name'].'/';
            }else if($key == 2){
                $ship_area .= $address[$key]['local_name'] .':'.$address[$key]['region_id'];
            }
            $ship_addr .= $address[$key]['local_name'] . ' ';
        }
        $order_info['tostr']       = implode(',',$tostr);
        $order_info['ship_area']   = $ship_area;
        $order_info['ship_addr']   = $ship_addr . $receive['address'];
        $order_info['weight']      = 0.00;
        $order_info['confirm']     = 'N';
        $order_info['status']      = 'dead';
        $order_info['pay_status']  = '0';
        $order_info['ship_status'] = '0';
        $order_info['user_status'] = 'null';
        $order_info['is_delivery'] =  'Y';
        $order_info['is_tax']      = 'false';
        $order_info['cost_tax']    = 0.000;
        $order_info['freight']     = 0.000;
        $order_info['is_protect']  = 'false';
        $order_info['payment']     = -1;
        $order_info['ip'] = getIP();
        $order_info['createtime'] = $time;
        unset($order_info['skus']);
        unset($order_info['region_path']);

        $third_party_order = array(
            'order_num' => $receive['yggc_order'],
            'member_id' => $members_id['member_id'],
            'createtime'=> $time
        );
        $third_order_id = M('third_party_order','sdb_','DB_CONFIG2')->add($third_party_order);      //插入third_order表
        $order_info['third_order_id'] = $third_order_id;

        $order_id = M('orders','sdb_','DB_CONFIG2')->add($order_info);                               //插入order表

        foreach($order_item as $key=>$val) {
            $order_item_id = M('order_items', 'sdb_', 'DB_CONFIG2')->add($val);                     //插入order_item表
        }

        $return_sku = array();
        foreach($sku_arr as $key=>$val){
            $return_sku[$key]['sku'] = $val['sku'];
            $return_sku[$key]['num'] = $val['num'];
            $return_sku[$key]['price'] = $val['price'];
            $return_sku[$key]['yanbao'] = array();
        }

        $res = array(
            "success" => "true",
            "result" => array(
                'mall_order_id' => $order_info['order_id'],
                'sku'           => $return_sku,
                'orderPrice'    => $receive['order_price'],
                'freight'       => 0
            )
        );
        exit(json_encode($res,JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE));
    }

    /**
     * 确认订单接口
     * URL http://api.shenhexin.com/api/order/confirm
     * Http Method GET
     * 1、获取接口参数access_token、order_id
     * 2、验证access_token，如果过期，则重新获取
     * 3、确认订单，恢复可编辑状态
     */
    public function confirm(){
        //$receive = json_decode(file_get_contents('php://input'),true);
        $receive = I('post.');
        A('Common')->checkAccessToken($receive['token']);                   //校验access_token
        A('Common')->errorMsg($receive['order_id'],'请检查输入是否有误');                 //校验order_id
        //判断是否重复确认订单
        $is_confirm = M('orders','sdb_','DB_CONFIG2')->where(array('order_id'=>$receive['order_id']))->field('is_confirm')->find();
        if($is_confirm['is_confirm']){
            A('Common')->errorMsg(0,'已确认订单');
        }

        $id = M('orders','sdb_','DB_CONFIG2')->where(array('order_id'=>$receive['order_id']))->setField('is_confirm',1);
        if($id){
            $res = array(
                'success' => 'true'
            );
        }else{
            $res = array(
                'success' => 'false',
                'desc' => '请检查输入是否有误'
            );
        }
        exit(json_encode($res,JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE));
    }

    /**
     * 取消订单接口
     * URL http://api.shenhexin.com/api/order/cancel
     * Http Method GET
     * 1、获取接口参数access_token、order_id
     * 2、验证access_token，如果过期，则重新获取
     * 3、取消订单
     */
    public function cancel(){
        //$receive = json_decode(file_get_contents('php://input'),true);
        $receive = I('post.');
        A('Common')->checkAccessToken($receive['token']);
        A('Common')->errorMsg($receive['order_id'],'请检查输入是否有误');

        //判断是否重复取消订单
        $is_confirm = M('orders','sdb_','DB_CONFIG2')->where(array('order_id'=>$receive['order_id']))->field('is_confirm')->find();
        if(!$is_confirm['is_confirm']){
            A('Common')->errorMsg(0,'已取消订单');
        }

        $id = M('orders','sdb_','DB_CONFIG2')->where(array('order_id'=>$receive['order_id']))->setField('is_confirm',0);
        if($id) {
            $res = array('success' => 'true');
        }else {
            $res = array('success' => 'false');
        }
        exit(json_encode($res,JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE));
    }

    /**
     * 查询订单接口
     * 【URL】 http://api.shenhexin.com/api/order/select
     * 【Http Method】 GET
     * 1、获取接口参数access_token、order_id
     * 2、验证access_token，如果过期，则重新获取
     * 3、查询订单
     * 4、pay_status: 0 未支付 1 已支付 5 退款
     */
    public function select(){
        //$receive = json_decode(file_get_contents('php://input'),true);
        $receive = I('post.');

        A('Common')->checkAccessToken($receive['token']);
        A('Common')->errorMsg($receive['order_id'],'error order_id');

        $sql = "SELECT a.cost_item,b.bn,b.nums,b.price FROM sdb_orders a JOIN sdb_order_items b ON a.order_id=b.order_id WHERE a.order_id=".$receive['order_id'];
        $orders = M('','','DB_CONFIG2')->query($sql);

        if(!$orders){
            A('Common')->errorMsg(0,'输入有误或无返回数据');
        }

        $status = M('orders','sdb_','DB_CONFIG2')->where(array('order_id'=>$receive['order_id']))->field('pay_status,cost_item')->find();

        $state = $status['pay_status'];
        if($status['pay_status'] != 0 || $status['pay_status'] != 1 || $status['pay_status'] != 5){
            $state = 0;
        }

        foreach($orders as $key=>$val){
            $new_orders[$key]['sku'] = $val['bn'];
            $new_orders[$key]['num'] = $val['nums'];
            $new_orders[$key]['price'] = $val['price'];
            $new_orders[$key]['yanbao'] = array();
        }
        $res = array(
            'success' => 'true',
            'result' => array(
                'order_id' => $receive['order_id'],
                'total_price' => $status['cost_item'],
                'state' => $state,
                'skus' => $new_orders,
                'return_skus' => array()
            )
        );
        exit(json_encode($res,JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES));
    }

    /**
     * 物流接口
     */
    public function track() {
        $receive = I('post.');
        A('Common')->checkAccessToken($receive['token']);
        A('Common')->errorMsg($receive['token'],'error order_id,请检查输入是否有误');

        $order_status = M('orders','sdb_','DB_CONFIG2')->where(array('order_id'=>$receive['order_id']))->field('is_confirm,createtime')->find();
        if(empty($order_status)){
            $res = array(
                'result' => array(
                    'success' => 'false',
                    'desc' => 'error order_id,请检查输入是否有误'
                )
            );
        }else if($order_status['is_confirm'] == 0){
            $res = array(
                'result' => array(
                    'order_id' => $receive['order_id'],
                    'track' => array(
                        0 => array(
                            'operate_time' => date('Y-m-d H:i:s',$order_status['createtime']),
                            'content' => '您提交了订单，请等待系统确认',
                            'operator' => '客户'
                        )
                    )
                )
            );
        }else if($order_status['is_confirm'] == 1){
            $res = array(
                'order_id' => $receive['order_id'],
                'track' => array(
                    0 => array(
                        'operate_time' => date('Y-m-d H:i:s',$order_status['createtime']),
                        'content' => '您提交了订单，请等待系统确认',
                        'operator' => '客户'
                    )
                )
            );
        }
        exit(json_encode($res,JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE));
    }

    /**
     * 对账接口
     * 【URL】http://api.shenhexin.com/api/order/checkr
     * 【Http Method】GET
     * 1、获取接口参数access_token、bdate、edate
     * 2、验证接口参数，如果过期，则重新获取
     * 3、查询账单信息
     * 4、pay_status: 0 未支付 1 已支付 5 退款
     */
    public function checkr(){
        //$receive = json_decode(file_get_contents('php://input'),true);
        $receive = I('post.');
        $access_token = $receive['token'];
        $bdate = strtotime($receive['bdate']) + 24*60*60;
        $edate = strtotime($receive['edate']) + 24*60*60;

        A('Common')->checkAccessToken($access_token);
        A('Common')->errorMsg($receive['bdate'],'请检查输入是否有误');
        A('Common')->errorMsg($receive['edate'],'请检查输入是否有误');
        $member_id = M('members','sdb_','DB_CONFIG2')->where(array('access_token'=>$access_token))->field('member_id')->find();
        $map['member_id'] = array('eq',$member_id['member_id']);
        $map['_string'] = 'createtime>'.$bdate .' AND createtime<'.$edate;

        $count = M('orders','sdb_','DB_CONFIG2')->where($map)->count();
        $orders = M('orders','sdb_','DB_CONFIG2')->where($map)->field('order_id,pay_status state,cost_item total_price,is_tax invoice_state')->select();
        foreach($orders as $key=>$order){
            $state = $order['state'];
            if($order['state'] != 0 || $order['state'] != 1 || $order['state'] != 5){
                $state = 0;
            }
            $orders[$key]['state'] = $state;
            if($order['invoice_state'] == 'false'){
                $orders[$key]['invoice_state'] = 0;
            }else{
                $order[$key]['invoice_state'] == 1;
            }
        }
        $_orders = array_values($orders);

        if($_orders){
            $res = array(
                'success' => 'true',
                'result'  => array(
                    'orders' => $_orders,
                    'num' => $count
                )
            );
        }else{
            $res = array(
                'success' => 'false',
                'desc' => '无数据返回'
            );
        }
        exit(json_encode($res,JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE));
    }
}